import jwt from "jsonwebtoken"

/**
 * 生成token
 * @param user
 * @returns {*}
 */
const generateAccessToken = (user) => {
    const config = useRuntimeConfig()

    return jwt.sign({ userId: user.id }, config.jwtAccessSecret, {
        expiresIn: '10m'
    })
}
/**
 * 生成刷新token
 * @param user
 * @returns {*}
 */
const generateRefreshToken = (user) => {
    const config = useRuntimeConfig()

    return jwt.sign({ userId: user.id }, config.jwtRefreshSecret, {
        expiresIn: '4h'
    })
}
//

export const decodeRefreshToken = (token) => {
    const config = useRuntimeConfig()

    try {
        return jwt.verify(token, config.jwtRefreshSecret)
    } catch (error) {
        return null
    }
}
export const decodeAccessToken = (token) => {
    const config = useRuntimeConfig()

    try {
        return jwt.verify(token, config.jwtAccessSecret)
    } catch (error) {
        return null
    }
}

// 给返回的http 返回cookie设置对应的值
export  const sendRefreshToken = (event,token)=>{
    setCookie(event,"refresh_token",token,{
        httpOnly: true,
        sameSite: true
    })
}

export const generateTokens = (user)=>{
    const accessToken = generateAccessToken(user)
    const refreshToken = generateRefreshToken(user)
    return {
        accessToken: accessToken,
        refreshToken: refreshToken
    }
}
